<script setup lang="ts">
import type { ApprovalProcessDetail } from '@/types/api'
import { reactive, ref } from 'vue'
import { getTaskByProcessInstanceId } from '@/api/workflow'
import ProcessInfoCard from '@/components/ProcessInfoCard.vue'
import { useSystemStore } from '@/store/system'
import { formatDate } from '@/utils/timeUtils'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '审批流程',
    navigationBarTextStyle: 'black',
    backgroundColor: '#f5f5f5',
  },
})

// 页面参数
const params = ref<{
  id?: string
  title?: string
}>({})

// 流程步骤接口
interface ProcessStep {
  id: string
  name: string
  assignee: string
  assigneeName: string
  status: 'pending' | 'running' | 'completed' | 'rejected'
  startTime?: string
  endTime?: string
  comment?: string
  order: number
}

const { bpmTaskStatusDict, fetchBpmTaskStatusDict } = useSystemStore()

// 流程信息
const processInfo = reactive<ApprovalProcessDetail>({
  name: '-',
  nameDetail: '-',
  applyTime: '-',
  applyName: '-',
  busNumber: '-',
  status: 0,
  statusDesc: '-',
  processFlowNode: [],
})

// 流程步骤
const processSteps = ref<ProcessStep[]>([])

// 加载状态
const loading = ref(false)

// 计算状态颜色
function getStatusColor(status: number) {
  // 统一转换为字符串进行比较，增强容错性
  const statusStr = String(status)

  switch (statusStr) {
    case '1':
      return 'text-[#2563eb]' // 待审批
    case '0':
      return 'text-[#FAAD14]' // 审批中
    case '2':
      return 'text-[#16a34a]' // 审批通过
    case '3':
      return 'text-[#dc2626]' // 审批不通过
    case '4':
      return 'text-[#9ca3af]' // 已取消
    case '5':
      return 'text-[#F5222D]' // 已退回
    case '6':
      return 'text-[#FA8C16]' // 委派中
    case '7':
      return 'text-[#13C2C2]' // 审批通过中
  }
}

// 监听页面加载
onLoad((options) => {
  // 判断字典是否为空，为空需要重新获取
  if (!bpmTaskStatusDict?.length) {
    fetchBpmTaskStatusDict()
  }
  params.value = options
  // 设置标题
  if (options.title) {
    const title = decodeURIComponent(options.title as string)
    uni.setNavigationBarTitle({
      title: `${title} - 审批流程`,
    })
  }

  // 加载流程数据
  loadProcessData()
})

// 模拟加载流程数据
async function loadProcessData() {
  try {
    loading.value = true
    const res = await getTaskByProcessInstanceId(params.value.id || '')
    if (res.data) {
      processInfo.name = res.data.name || '-'
      processInfo.nameDetail = res.data.nameDetail || '-'
      processInfo.applyTime = res.data.applyTime || '-'
      processInfo.applyName = res.data.applyName || '-'
      processInfo.busNumber = res.data.busNumber || '-'
      processInfo.status = res.data.status || 0
      processInfo.statusDesc = res.data.statusDesc || ''
      processInfo.processFlowNode = res.data.processFlowNode || []
      // processInfo.processFlowNode = [
      //   {
      //     nodeName: '发起人确认',
      //     approvalName: ['系统管理员'],
      //     approvalTimeStart: '2025-11-26 11:11:36',
      //     approvalTimeEnd: '2025-11-26 11:11:36',
      //     consuming: 61,
      //     approvalOpinion: '同意',
      //     status: 2,
      //     statusDesc: '审批通过',
      //   },
      //   {
      //     nodeName: '审批1',
      //     approvalName: ['系统管理员', '王娇', '安绍龙'],
      //     approvalTimeStart: '2025-11-26 11:11:36',
      //     approvalTimeEnd: null,
      //     consuming: null,
      //     approvalOpinion: null,
      //     status: 1,
      //     statusDesc: '审批中',
      //   },
      //   {
      //     nodeName: '审批2',
      //     approvalName: ['张三'],
      //     approvalTimeStart: '2025-11-26 10:00:00',
      //     approvalTimeEnd: null,
      //     consuming: null,
      //     approvalOpinion: null,
      //     status: 0,
      //     statusDesc: '待审批',
      //   },
      //   {
      //     nodeName: '审批3',
      //     approvalName: ['李四'],
      //     approvalTimeStart: '2025-11-26 09:00:00',
      //     approvalTimeEnd: '2025-11-26 09:15:00',
      //     consuming: 900,
      //     approvalOpinion: '不同意，需要补充材料',
      //     status: 3,
      //     statusDesc: '审批不通过',
      //   },
      //   {
      //     nodeName: '审批4',
      //     approvalName: ['王五'],
      //     approvalTimeStart: '2025-11-26 08:00:00',
      //     approvalTimeEnd: '2025-11-26 08:30:00',
      //     consuming: 1800,
      //     approvalOpinion: null,
      //     status: 4,
      //     statusDesc: '已取消',
      //   },
      //   {
      //     nodeName: '审批5',
      //     approvalName: ['赵六'],
      //     approvalTimeStart: '2025-11-25 16:00:00',
      //     approvalTimeEnd: '2025-11-25 16:30:00',
      //     consuming: 1800,
      //     approvalOpinion: '退回修改',
      //     status: 5,
      //     statusDesc: '已退回',
      //   },
      //   {
      //     nodeName: '审批6',
      //     approvalName: ['孙七', '周八'],
      //     approvalTimeStart: '2025-11-25 14:00:00',
      //     approvalTimeEnd: null,
      //     consuming: null,
      //     approvalOpinion: null,
      //     status: 6,
      //     statusDesc: '委派中',
      //   },
      //   {
      //     nodeName: '审批7',
      //     approvalName: ['吴九', '郑十'],
      //     approvalTimeStart: '2025-11-25 13:00:00',
      //     approvalTimeEnd: null,
      //     consuming: null,
      //     approvalOpinion: null,
      //     status: 7,
      //     statusDesc: '审批通过中',
      //   },
      // ]
    }
  }
  catch (error) {
    console.error('加载流程数据失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <view class="process-container min-h-screen bg-gray-50">
    <!-- 加载状态 -->
    <view v-if="loading" class="h-60 flex items-center justify-center">
      <text class="text-gray-500">加载中...</text>
    </view>

    <template v-else>
      <!-- 流程基本信息 -->
      <ProcessInfoCard :process-info="processInfo" />

      <!-- 流程进度 -->
      <view class="mb-4 bg-white p-4">
        <view class="mb-4">
          <text class="text-base text-gray-900 font-semibold">审批流程</text>
        </view>

        <view class="space-y-4">
          <wd-steps :active="1" vertical>
            <wd-step
              v-for="(step, index) in processInfo.processFlowNode"
              :key="index + step.nodeName"
            >
              <template #icon>
                <ApprovalStatusTag :value="step.status" type="icon" class="mr-[5rpx] mt-[5rpx]" />
              </template>
              <template #title>
                <view class="flex items-center justify-between">
                  <text class="text-sm text-gray-900 font-medium">{{ step.nodeName }}</text>
                  <ApprovalStatusTag :value="step.status" type="color" />
                </view>
              </template>
              <template #description>
                <view class="min-w-0 flex-1 pb-4">
                  <view class="text-xs text-gray-500 space-y-1">
                    <view>审批人：{{ step.approvalName.join('、') }}</view>
                    <view v-if="step.approvalTimeStart">
                      开始时间：{{ formatDate(step.approvalTimeStart) }}
                    </view>
                    <view v-if="step.approvalTimeEnd">
                      完成时间：{{ formatDate(step.approvalTimeEnd) }}
                    </view>
                    <view v-if="step.approvalOpinion" class="mt-2">
                      <text class="text-gray-600">审批意见：</text>
                      <text class="text-gray-800">{{ step.approvalOpinion }}</text>
                    </view>
                  </view>
                </view>
              </template>
            </wd-step>
          </wd-steps>
        </view>
      </view>
    </template>
  </view>
</template>

<style lang="scss" scoped>
// 所有样式都已使用UnoCSS类实现
</style>
